import os
import re
import sys

import requests

# 基础信息
_runDir_ = os.path.split(os.path.realpath(__file__))[0]
__auther__ = "bgcls"
__repo__ = "auto-service"


def getFiles(url, trys=0):
    data = requests.get(url).text
    if data.find("法律") > 0 and data.find("违法") > 0 and data.find("/.ver") == -1:
        # print(data)
        if trys > 5:
            raise ValueError(f"更新文件失败,{url}")
        return getFiles(url, trys=trys + 1)
    else:
        return data


def getVersionInfo(V=0):
    url = f"https://gitee.com/api/v5/repos/{__auther__}/{__repo__}/tags"
    try:
        if not hasattr(getVersionInfo, '__data__'):
            getVersionInfo.__data__ = requests.get(url).json()

        if type(V) == str:
            if V == 'master':
                url = f"https://gitee.com/api/v5/repos/{__auther__}/{__repo__}/commits?page=1&per_page=1"
                data = requests.get(url).json()
                return {"name": "master", "commit": {"sha": data[0]}}
            try:
                return list(filter(lambda x: x['name'] == V, getVersionInfo.__data__))[0]
            except:
                return getVersionInfo.__data__[-1]
        return getVersionInfo.__data__[V]
    except:
        print("检测版本失败！")
        exit(1)


def fileNameCheck(name: str):
    if name.find("_config") > 0:
        return False
    if name.find("/") == -1:
        return True
    elif name.find("core/") == 0:
        return True
    elif name.find("demo/") == 0:
        return True

    return False


def updateFiles(fromVersion, updateVersion):
    # url = f"https://gitee.com/bgcls/auto-service/raw/{newVersion}"
    compareUrl = f"https://gitee.com/api/v5/repos/{__auther__}/{__repo__}/compare/{fromVersion['commit']['sha']}...{updateVersion['commit']['sha']}"
    data = requests.get(compareUrl).json()
    updateFileList = list(filter(lambda obj: fileNameCheck(obj['filename']), data['files']))
    for change in updateFileList:
        if change['status'] in ['modified', 'added']:
            print("download: " + change['filename'])
            getFiles(change['raw_url'])
        else:
            print(" delete : " + change['filename'])
            os.remove(change['filename'])


isFirstInstall = False

if not os.path.exists(_runDir_ + "/core"):
    os.mkdir(_runDir_ + "/core")
    isFirstInstall = True
oldVersion = "v1.0.0.0"

if os.path.exists(_runDir_ + "/.ver"):
    with open(_runDir_ + "/.ver", "r") as f:
        oldVersion = f.readline().strip()

newVersionData = getVersionInfo()
newVersion = newVersionData['name']
command = ' '.join(sys.argv) + " "
forceUseLatest = command.find(" -r ") >= 0  # 使用master最新版
forceUpdate = command.find(" -f ") >= 0
forceInstall = command.find(" -i ") >= 0
commonMode = forceUseLatest or forceUpdate or forceInstall
commonMode = not commonMode

pull_start_version = getVersionInfo(oldVersion)

if commonMode:
    print(f"当前版本暂无更新,当前版本为:{oldVersion}")
    exit(0)
if forceUpdate: pull_start_version = getVersionInfo(1)

if forceUseLatest:
    print("即将安装master分支源码")
    pull_start_version = getVersionInfo(-1)
elif forceInstall:
    print("即将安装最新版本")
    print(f"最新版本:{newVersion}")
    pull_start_version = getVersionInfo(-1)
else:
    print(f"即将升级版本")
    print(f"升级内容: {newVersionData['message']}")
updateFiles(pull_start_version, newVersionData)

with open(_runDir_ + "/.ver", "w") as f:
    f.write(newVersion)
if forceInstall or forceUseLatest:
    if forceUseLatest:
        newVersion = "master"
    print(f"安装{newVersion}完成")
else:
    if forceUpdate:
        print(f"强制升级完成,当前版本为{newVersion}.")
    else:
        print(f"升级完成,{oldVersion}->{newVersion}完成")

if isFirstInstall:
    if not os.path.exists("core/update.py"):
        os.rename('update.py', 'core/update.py')
    else:
        os.remove('update.py')
    print("已将 update.py文件删除，下次使用请使用命令 python3 -m core.update 代替")

